<template>
	<view class="container">
		<view class="header">
			<text class="title">{{newsDetail.title || '无标题'}}</text>
			<view class="meta">
				<text class="source">{{newsDetail.src || '未知来源'}}</text>
				<text class="time">{{newsDetail.time}}</text>
			</view>
		</view>

		<image v-if="newsDetail.pic" :src="newsDetail.pic" mode="widthFix" class="detail-image"></image>

		<view class="content">
			<rich-text v-if="newsDetail.content" :nodes="newsDetail.content"></rich-text>
			<text v-else>暂无内容</text>
		</view>

		<view v-if="loading" class="loading">
			<text>加载中...</text>
		</view>
	</view>
</template>

<script>
	const db = uniCloud.database();

	export default {
		data() {
			return {
				newsDetail: {
					title: '',
					src: '',
					time: '',
					pic: '',
					content: ''
				},
				loading: false
			}
		},
		onLoad(options) {
			console.log('接收到的参数:', options); // 检查跳转参数
			if (options.id) {
				this.getNewsDetail(options.id);
			}
		},
		methods: {
			async getNewsDetail(id) {
				this.loading = true;
				try {
					const res = await db.collection('news').doc(id).get();
					console.log('完整数据库响应:', res);

					if (res.result.data && res.result.data.length > 0) {
						// 取数组第一项作为详情数据
						const rawData = res.result.data[0];
						this.newsDetail = {
							title: rawData.title,
							src: rawData.src,
							time: rawData.time,
							pic: rawData.pic,
							content: rawData.content
						};
					} else {
						uni.showToast({
							title: '新闻不存在',
							icon: 'none'
						});
						setTimeout(() => uni.navigateBack(), 1500);
					}
				} catch (e) {
					console.error('加载失败:', e);
					uni.showToast({
						title: '加载失败',
						icon: 'none'
					});
				} finally {
					this.loading = false;
				}
			},
		}
	}
</script>
<style lang="scss">
	.container {
		padding: 30rpx;
		background-color: #fff;
		min-height: 100vh;
	}

	/* 标题样式 */
	.header {
		margin-bottom: 40rpx;

		.title {
			font-size: 40rpx;
			font-weight: bold;
			line-height: 1.5;
			color: #333;
		}

		.meta {
			display: flex;
			color: #999;
			font-size: 26rpx;

			.source {
				margin-right: 30rpx;
			}
		}
	}

	/* 图片样式 */
	.detail-image {
		width: 100%;
		border-radius: 12rpx;
		margin-bottom: 40rpx;
	}

	/* 正文样式 */
	.content {
		font-size: 32rpx;
		line-height: 1.8;

		.deep .img {
			/* 确保图片自适应 */
			max-width: 100% !important;
			height: auto !important;
			margin: 20rpx 0;
			border-radius: 8rpx;
		}
	}

	/* 加载动画 */
	.loading {
		padding: 40rpx 0;
		text-align: center;
	}
</style>